import React, {useState, useEffect} from 'react';
import {Cascader} from 'antd';
import _ from 'lodash'
import {get} from "../../service";

function AreaCascader(props) {
    const [options, setOptions] = useState([])
    const [defaultValue, setDefaultValue] = useState(props.defaultValue);
    useEffect(() => {
        get('/api/area/province').then((res) => {
          res.records.map(item => (item.isLeaf = false))
            setOptions(res.records)
            //有默认值的时候自动获取市根区
            if (defaultValue && defaultValue.length) {
                onInit(res.records)
            }
        })
    }, []);
    /**
     * records:要被超扎破的對象
     * inde：defalutVlue的下标
     */
    const onInit=(records, index=0) => {
        const item = _.find(records, (item) => item.value == defaultValue[index])||{}
        if(index==2)return
        onRequestCityOrRegion(item).then(data => {
            onInit(data, index + 1)
        })
    }
    //动态加载市跟区
    const onRequestCityOrRegion = (parent) => {
        const isLeaf = String(parent.id).length == 2 ? true : false
        return get(`/api/area/${isLeaf ? 'region' : 'city'}`, {pid: parent.id}).then(data => {
            data.records.map(item => item.isLeaf = isLeaf)
            parent.children = data.records
            setOptions([...options])
            return data.records
        })
    }
    const loadData = (selectedOptions = []) => {
        const selectedOption = selectedOptions[selectedOptions.length - 1]
        onRequestCityOrRegion(selectedOption)
    }
    return (
        <Cascader
            placeholder='省/市/区'
            options={options}       // 确保正确使用
            loadData={loadData}     // 确保正确使用
            onChange={props.onChange}
            defaultValue={defaultValue}
            value={defaultValue}
        />
    );
}

export default AreaCascader;
